package com.zjt.smart.api;

import android.support.annotation.NonNull;

import com.zjt.smart.api.intercepter.CacheInterceptor;
import com.zjt.smart.api.intercepter.HeaderInterceptor;
import com.zjt.smart.api.intercepter.HttpLoggingInterceptor;
import com.zjt.smart.api.server.BaiduServer;
import com.zjt.smart.api.server.BaseServer;
import com.zjt.smart.app.Config;
import com.zjt.smart.util.LogUtil;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class ApiManager {

    private Retrofit baiduRetrofit;

    private static class ClassHolder {
        private static ApiManager INSTANCE = new ApiManager();
    }

    private ApiManager() {
        baiduRetrofit = createBulider(BaiduServer.getInstance()).build();
    }

    private Retrofit.Builder createBulider(BaseServer server) {
        String domain = server.getDomain();
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(message -> LogUtil.http(message));
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        HeaderInterceptor headerInterceptor = new HeaderInterceptor();
        headerInterceptor.setHeader(server.getHeader());

        OkHttpClient client = new OkHttpClient
                .Builder()
                .readTimeout(Config.HTTP_TIMEOUT, TimeUnit.SECONDS)
                .addInterceptor(headerInterceptor)
                .addInterceptor(loggingInterceptor)
                .addInterceptor(new CacheInterceptor())
                .build();

        Retrofit.Builder builder = new Retrofit
                .Builder()
                .baseUrl(domain)
                .addConverterFactory(GsonConverterFactory.create())
                .client(client);

        return builder;
    }

    public static <T> T create(@NonNull final Class<T> api) {
        if (BaiduApi.class == api) {
            return ClassHolder.INSTANCE.baiduRetrofit.create(api);
        } else {
            return null;
        }
    }

    public static BaseServer getServer(Class api) {
        if (BaiduApi.class == api) {
            return BaiduServer.getInstance();
        } else {
            return null;
        }
    }
}
